package com.wondream.myframework.app.common.util;

import java.awt.*;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * bean对象转map
 */
public class BeanToMapUtils {

    public static Map<String, Object> beanToMap(Object bean) {

        // 1.初始化map
        Map<String, Object> result = new HashMap<>();
        if (bean == null) {
            return result;
        }
        // 2.获取属性
        Field[] fields = bean.getClass().getDeclaredFields();
        setMap(fields, result, bean);
        // 3.获取父类属性
        fields = bean.getClass().getSuperclass().getDeclaredFields();
        setMap(fields, result, bean);
        return result;
    }

    private static Map<String, Object> setMap(Field[] fields, Map<String, Object> result, Object bean) {
        if (fields == null || fields.length == 0) {
            return result;
        }
        for (Field field : fields) {
            if (field.isSynthetic()) {
                continue;
            }
            boolean accessible = field.isAccessible();
            field.setAccessible(true);
            try {
                if (null != field.get(bean)) {
                    result.put(field.getName(), field.get(bean));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            field.setAccessible(accessible);
        }
        return result;
    }

    public static void main(String[] args) {
        Point point = new Point();
        point.x = 1;
        point.y = 2;
        Map<String, Object> result = BeanToMapUtils.beanToMap(point);
        System.out.println(result);
    }
}
